package com.wmlive.hhvideo.heihei.bells.fragment;

import android.content.Context;
import android.support.annotation.NonNull;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.text.Editable;
import android.text.TextUtils;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.jakewharton.rxbinding2.widget.RxTextView;
import com.wmlive.hhvideo.application.DCApplication;
import com.wmlive.hhvideo.common.base.DcBaseFragment;
import com.wmlive.hhvideo.common.navigator.Navigator;
import com.wmlive.hhvideo.heihei.beans.bell.BellMessage;
import com.wmlive.hhvideo.heihei.beans.main.VideoCommentResponse;
import com.wmlive.hhvideo.heihei.bells.adapter.BellAdapter;
import com.wmlive.hhvideo.heihei.bells.callback.BellMessageClickCallBack;
import com.wmlive.hhvideo.heihei.bells.presenter.BellCommentPresenter;
import com.wmlive.hhvideo.heihei.bells.presenter.BellsPresenter;
import com.wmlive.hhvideo.heihei.bells.presenter.FollowPresenter;
import com.wmlive.hhvideo.heihei.bells.view.BellCommentView;
import com.wmlive.hhvideo.heihei.bells.view.BellsView;
import com.wmlive.hhvideo.heihei.bells.view.FollowView;
import com.wmlive.hhvideo.heihei.db.manager.IMMessageDefaultDBManager;
import com.wmlive.hhvideo.heihei.db.manager.IMMessageUserDBManager;
import com.wmlive.hhvideo.heihei.login.AccountUtil;
import com.wmlive.hhvideo.utils.CollectionUtil;
import com.wmlive.hhvideo.utils.KLog;
import com.wmlive.hhvideo.utils.StringUtils;
import com.wmlive.hhvideo.utils.ToastUtil;
import com.wmlive.hhvideo.widget.refreshrecycler.RefreshRecyclerView;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import butterknife.OnTextChanged;
import cn.wmlive.hhvideo.R;
import io.reactivex.Observable;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;

/**
 * 承载消息列表的fragment
 * Created by vhawk on 2017/7/5.
 */
public class BellsFragment extends DcBaseFragment implements BellsView, RefreshRecyclerView.OnLoadMoreListener, BellMessageClickCallBack, BellCommentView, FollowView, SwipeRefreshLayout.OnRefreshListener {

    @BindView(R.id.recycle_bell)
    RefreshRecyclerView recyclerView;
    @BindView(R.id.rl_comment)
    FrameLayout frameComment;
    @BindView(R.id.view_empty)
    View viewCommentEmpty;
    @BindView(R.id.etComment)
    EditText etComment;
    @BindView(R.id.tvSend)
    TextView tvSend;

    @BindView(R.id.rl_title)
    RelativeLayout rlTitle;
    private BellAdapter adapter;
    private BellsPresenter bellsPresenter;
    private String commentUserName;
    private long commentUserId;
    private long commentVideoId;
    private static final String TAG = "BellsFragment";
    private BellCommentPresenter commentPresenter;
    private FollowPresenter followPresenter;

    @Override
    public int getLayoutId() {
        return R.layout.fragment_bells;
    }

    @Override
    protected void initData() {
        super.initData();
        initRecycle();
        initPresenter();
        initView();
    }

    private void initView() {
//        RelativeLayout.LayoutParams l = (RelativeLayout.LayoutParams) rlTitle.getLayoutParams();
//        l.topMargin = DeviceUtils.getStatusBarHeight(getActivity());
        viewCommentEmpty.setOnClickListener(this);
        initCommentControl();
    }

    /**
     * 初始化presenter配置
     */
    private void initPresenter() {
        bellsPresenter = new BellsPresenter(this);
        bellsPresenter.readBellMessage("", (long) 0);

        commentPresenter = new BellCommentPresenter(this);
        followPresenter = new FollowPresenter(this);
        addPresenter(bellsPresenter, commentPresenter, followPresenter);
    }

    /**
     * 初始化评论输入控制
     */
    private void initCommentControl() {
        Observable<Boolean> commentObservable = RxTextView.textChanges(etComment).map(new Function<CharSequence, Boolean>() {

            @Override
            public Boolean apply(@NonNull CharSequence charSequence) throws Exception {

                return !TextUtils.isEmpty(charSequence);
            }
        }).skip(1);
        commentObservable.subscribe(new Consumer<Boolean>() {
            @Override
            public void accept(Boolean enable) throws Exception {
                enableSendButton(enable);
            }
        });

    }

    /**
     * 评论发送按钮控制
     *
     * @param enable true 可点击 false 不可点击
     */
    private void enableSendButton(Boolean enable) {
        tvSend.setEnabled(enable);
    }

    /**
     * recyclerView 初始配置
     */
    private void initRecycle() {
        adapter = new BellAdapter(new ArrayList<BellMessage>(), recyclerView);
        adapter.setEmptyStr(R.string.bell_message_null);
        adapter.setShowImg(true);
        adapter.setClickCallBack(this);
        recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        recyclerView.setAdapter(adapter);
        recyclerView.setLoadMoreEnable(false);
        recyclerView.setRefreshEnable(true);
        recyclerView.setOnRefreshListener(this);
        recyclerView.setOnLoadMoreListener(this);
    }

    @Override
    protected void onSingleClick(View v) {
        switch (v.getId()) {
            case R.id.view_empty:
                finishComment();
                break;
        }
    }

    /**
     * 关闭评论框
     */
    private void finishComment() {
        etComment.setText("");
        frameComment.setVisibility(View.GONE);
        closeSoftKeyBord(etComment, getActivity());
    }

    public static Fragment newInstance() {
        Fragment fragment = new BellsFragment();
        return fragment;
    }

    @Override
    public void addBellMessage(boolean hasMore, List<BellMessage> bellMessageList, boolean needRefresh) {
        if (CollectionUtil.isEmpty(adapter.getDataContainer()) && CollectionUtil.isEmpty(bellMessageList)) {
            adapter.setEmptyStr(R.string.bell_message_null);
            adapter.setShowImg(true);
            adapter.addData(true,null);
        } else {
            adapter.addData(needRefresh, bellMessageList, hasMore);
        }

    }

    @Override
    public void onLoadMore() {
        if (adapter != null && !CollectionUtil.isEmpty(adapter.getDataContainer())) {
            BellMessage bellMessage = adapter.getDataContainer().get(adapter.getDataContainer().size() - 1);
            if (bellMessage != null){
                bellsPresenter.readBellMessage(String.valueOf(bellMessage.getCreate_time()), bellMessage.getListid());
            }
        }
    }

    @Override
    public void navigateToAuthorHomePage(long userId, String messageId) {
        if (userId > 0) {
            Navigator.getInstance().navigateToOtherUserHome(getActivity(), false, userId);
        }
    }

    @Override
    public void navigateToActivity(String url, String messageId) {
        Navigator.getInstance().bannerLink(getActivity(), url);
    }

    @Override
    public void replyComment(long userId, long videoId, String nickName, String messageId) {
        frameComment.setVisibility(View.VISIBLE);
        etComment.requestFocus();
        etComment.setHint("回复" + nickName);
        showSoftKeyboard(etComment, getActivity());
        commentUserName = nickName;
        commentUserId = userId;
        commentVideoId = videoId;

        RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT);
        layoutParams.addRule(RelativeLayout.ABOVE, R.id.ll_comment_input);
        viewCommentEmpty.setLayoutParams(layoutParams);
        viewCommentEmpty.setVisibility(View.VISIBLE);

    }

    @Override
    public void followAuthor(long userId, int position, String messageId) {
        followPresenter.followUser(userId, position, messageId);
    }

    @Override
    public void unFollowAuthor(long userId, int position, String messageId) {
        followPresenter.unFollowUser(userId, position, messageId);
    }



    /**
     * 打开软键盘
     *
     * @param view
     * @param mContext
     */
    private void showSoftKeyboard(View view, Context mContext) {
        if (view.requestFocus()) {
            InputMethodManager imm = (InputMethodManager) mContext.getSystemService(Context.INPUT_METHOD_SERVICE);
            imm.showSoftInput(view, InputMethodManager.SHOW_IMPLICIT);
        }
    }

    /**
     * 关闭软键盘
     *
     * @param mEditText
     * @param mContext
     */
    private void closeSoftKeyBord(EditText mEditText, Context mContext) {
        InputMethodManager imm = (InputMethodManager) mContext.getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(mEditText.getWindowToken(), 0);
    }

    /**
     * 检测评论输入字符
     *
     * @param editable
     */
    @OnTextChanged(value = R.id.etComment, callback = OnTextChanged.Callback.AFTER_TEXT_CHANGED)
    public void onCommentTextChanged(Editable editable) {
        double length = StringUtils.length(editable.toString());
        KLog.v(TAG, "length = " + length);
        if (length > 100) {
            int deleteCount = computeDeleteStringCount(editable.toString());
            KLog.v(TAG, "deleteCount = " + deleteCount);
            editable.delete(editable.toString().length() - deleteCount, editable.toString().length());
            ToastUtil.showToast(R.string.comment_content_length_limit);
        }
    }

    /**
     * 评论发送点击
     */
    @OnClick(R.id.tvSend)
    public void onSendClick() {
        String commentString = etComment.getText().toString();
        commentString = "@ " + commentUserName + ":" + commentString;
        commentPresenter.commentVideo(commentVideoId, commentString, "", commentUserId);
    }

    @OnClick(R.id.iv_back)
    public void onBackPress() {
        getActivity().finish();
    }

    /**
     * 计算截取字符串长度
     *
     * @param str 原始字符串
     * @return 截取掉字符串的长度
     */
    private int computeDeleteStringCount(String str) {
        int count = 0;
        double length = StringUtils.length(str);
        KLog.v(TAG, "raw length = " + length);
        while (length > 100) {
            String subStr = str.substring(str.length() - count);
            length = StringUtils.length(str) - StringUtils.length(subStr);
            count++;
            KLog.v(TAG, "sublength = " + length);
            KLog.v(TAG, "count = " + count);
        }
        count--;
        return count;
    }

    @Override
    public void handleCommentSucceed(VideoCommentResponse comment) {
        ToastUtil.showToast("评论成功");
        finishComment();
    }

    @Override
    public void handleCommentFailure(String message) {
        ToastUtil.showToast(message);
    }

    @Override
    public void handleFollowSucceed(int position) {
        adapter.followSucceed(position);
    }

    @Override
    public void handleFollowFailure(String message) {
        ToastUtil.showToast(message);
    }

    @Override
    public void handleUnFollowSucceed(int position) {
        adapter.unFollowSucceed(position);
    }

    @Override
    public void handleUnFollowFailure(String message) {
        ToastUtil.showToast(message);
    }

    @Override
    public void onRefresh() {
        bellsPresenter.readBellMessage("", (long) 0);
    }
}
